//
//  AddImageView.m
//  VideoData
//
//  Created by pro1 on 2019/3/7.
//  Copyright © 2019 pro1. All rights reserved.
//

#import "AddImageView.h"
#import "AddImageCollectionViewCell.h"
#import "AddImageHeader.h"
#import <CoreText/CoreText.h>


#define MaxSelectedImageCount 9
#define NormalImagePickingTag 1045
#define ModifiedImagePickingTag 1046
#define MultipleImagePickingTag 1047
#define SingleImagePickingTag 1048

static QMUIAlbumContentType const kAlbumContentType = QMUIAlbumContentTypeAll;

@interface AddImageView ()<UICollectionViewDataSource,UICollectionViewDelegate,QMUIAlbumViewControllerDelegate,QMUIImagePickerViewControllerDelegate,QMUIImagePickerPreviewViewControllerDelegate>

@property (strong,nonatomic) UICollectionView *collectionView;
@property (assign,nonatomic) CGSize itemSize;
@property (assign,nonatomic) CGFloat margin;
@property (strong,nonatomic) UIButton *canelButton;
@property (assign,nonatomic) CGPoint beginPoint;

@end



@implementation AddImageView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.selectedItem = 0;
        [self addSubview:self.canelButton];
        self.itemSize = CGSizeMake((NSInteger)(self.frame.size.width - 40)/3, (NSInteger)(self.frame.size.width - 40)/3);
        self.margin = 10;
        [self addSubview:self.collectionView];
    }
    return self;
}

- (UIButton *)canelButton{
    if (!_canelButton) {
        _canelButton  = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.frame.size.width, 24)];
        _canelButton.backgroundColor = [UIColor whiteColor];
        [_canelButton setImage:[UIImage imageNamed:@"上拉按钮"] forState:UIControlStateNormal];
        _canelButton.imageView.contentMode = UIViewContentModeScaleAspectFit;
        _canelButton.imageEdgeInsets = UIEdgeInsetsMake(6, 0, 6, 0);
        _canelButton.adjustsImageWhenHighlighted = NO;
        UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(panHandle:)];
        [_canelButton addGestureRecognizer:pan];
        [_canelButton setShadow:CGSizeMake(0,0.5) corner:0 opacity:1 color:[UIColor whiteColor] shadowColor:UIColorMakeWithHex(@"#EEEEEE") shadowRadius:6];
    }
    return _canelButton;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    self.canelButton.frame = CGRectMake(0, 0, self.frame.size.width, 24);
    self.collectionView.frame = CGRectMake(0, 24, self.frame.size.width, self.frame.size.height - 24);
}

- (void)setCellStyle:(CellStyle)cellStyle{
    _cellStyle = cellStyle;
    weakify(self);
    [self.collectionView setCollectionViewLayout:[self returnNewLayout]];
    switch (_cellStyle) {
        case CellStyleFont:{
            [AddImageView getDataWith:CellStyleFont datablock:^(NSMutableArray *returnList) {
                strongify(self)
                self.collectioData = returnList;
            }];
        }break;
        case CellStyleBGColor:{
            [AddImageView getDataWith:CellStyleBGColor datablock:^(NSMutableArray *returnList) {
                strongify(self)
                self.collectioData = returnList;
            }];
        }break;
        case CellStyleImage:{
            [AddImageView getDataWith:CellStyleImage datablock:^(NSMutableArray *returnList) {
                strongify(self)
                self.collectioData = returnList;
            }];
        }break;
        case CellStyleTemplate:{
            [AddImageView getDataWith:CellStyleTemplate datablock:^(NSMutableArray *returnList) {
                strongify(self)
                self.collectioData = returnList;
            }];
        }break;
        case CellStyleTheSeal:{
            [AddImageView getDataWith:CellStyleTheSeal datablock:^(NSMutableArray *returnList) {
                strongify(self)
                self.collectioData = returnList;
            }];
        }break;
            
        default:
            break;
    }
}

- (void)setSelectedItem:(NSInteger)selectedItem{
    _selectedItem = selectedItem;
    if (_collectionView) {
        [self.collectionView reloadData];
    }
}

- (void)setCollectioData:(NSArray *)collectioData{
    _collectioData = collectioData;
    if (_collectioData) {
        [self.collectionView reloadData];
    }
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0) collectionViewLayout:[self returnNewLayout]];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor colorWithRed:248/255.0 green:248/255.0 blue:248/255.0 alpha:1.0];
        [_collectionView registerClass:[AddImageCollectionViewCell class] forCellWithReuseIdentifier:NSStringFromClass([AddImageCollectionViewCell class])];
        [_collectionView registerClass:[AddImageHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:NSStringFromClass([AddImageHeader class])];
    }
    return _collectionView;
}

- (UICollectionViewFlowLayout *)returnNewLayout{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = self.itemSize;
    layout.minimumLineSpacing = self.margin;
    layout.minimumInteritemSpacing = self.margin;
    layout.sectionInset = UIEdgeInsetsMake(self.margin, self.margin, self.margin, self.margin);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
//    if (self.cellStyle == CellStyleImage) {
//        layout.headerReferenceSize = CGSizeMake(self.frame.size.width, 35);
//    }
    return layout;
}

#pragma mark - <UICollectionViewDataSource,UICollectionViewDelegate>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.collectioData ? self.collectioData.count : 0;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    AddImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([AddImageCollectionViewCell class]) forIndexPath:indexPath];
    cell.style = self.cellStyle;
    if (self.cellStyle == CellStyleImage && indexPath.row < 3) {
        cell.selected = NO;
    }
    else{
        cell.selected = (self.selectedItem == indexPath.row) ? YES : NO;
    }
    cell.contentValue = self.collectioData ? self.collectioData[indexPath.row] : nil;
    return cell;
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader] && self.cellStyle == CellStyleImage) {
//        AddImageHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:NSStringFromClass([AddImageHeader class]) forIndexPath:indexPath];
//        header.sectionHeaderBlock = ^(NSInteger index) {
//            NSLog(@"请求网络数据");
//        };
//        return header;
//    }
//    return nil;
//}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    self.selectedItem = indexPath.row;
    if (self.cellStyle == CellStyleImage && indexPath.row == 0) {
//        NSLog(@"跳转到相册");
        // 创建一个 QMUIAlbumViewController 实例用于呈现相簿列表
        QMUIAlbumViewController *albumViewController = [[QMUIAlbumViewController alloc] init];
        albumViewController.albumViewControllerDelegate = self;
        albumViewController.contentType = kAlbumContentType;
        albumViewController.title = @"选择图片";
        albumViewController.view.tag = 1045;
        UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:albumViewController];
        // 获取最近发送图片时使用过的相簿，如果有则直接进入该相簿
        [albumViewController pickLastAlbumGroupDirectlyIfCan];
        [[self getViewcontrollerView:self] presentViewController:navigationController animated:YES completion:NULL];
    }
    else if (self.cellStyle == CellStyleImage && indexPath.row == 1){
        if (self.userSelectedBlock) {
            NSInteger index = arc4random()%self.collectioData.count;
            self.selectedItem = index;
            self.userSelectedBlock(self.cellStyle,index,self.collectioData[index]);
        }
    }
    else if (self.cellStyle == CellStyleImage && indexPath.row == 2){
        self.cellStyle = CellStyleImage;
    }
    else{
        if (self.userSelectedBlock) {
            self.userSelectedBlock(self.cellStyle,indexPath.row,self.collectioData[indexPath.row]);
        }
    }
}

-(void)panHandle:(UIPanGestureRecognizer *)pan{
    if (pan.state == UIGestureRecognizerStateEnded) {
        
    }
    else if (pan.state == UIGestureRecognizerStateBegan){
        _beginPoint = [pan translationInView:self];
    }
    else if (pan.state == UIGestureRecognizerStateChanged){
        CGFloat length = [pan translationInView:self].y - _beginPoint.y;
        CGRect frame = self.frame;
        frame.size.height -= length;
        frame.origin.y += length;
        if (frame.size.height <= 25) {
            frame.size.height = 25;
            frame.origin.y = SCREEN_HEIGHT - SafeAreaInsetsConstantForDeviceWithNotch.bottom - 49 - 25;
        }
        else if (frame.size.height >= SCREEN_HEIGHT/2){
            frame.size.height = SCREEN_HEIGHT/2;
            frame.origin.y = SCREEN_HEIGHT - SafeAreaInsetsConstantForDeviceWithNotch.bottom - 49 - SCREEN_HEIGHT/2;
        }
        
        self.frame = frame;
        _beginPoint = [pan translationInView:self];
    }
}

+(void)getDataWith:(CellStyle)cellStyle datablock:(void(^)(NSMutableArray *returnList))returnListBlock{
    NSMutableArray *returnList = [[NSMutableArray alloc] init];
    if (cellStyle == CellStyleFont) {
        [returnList addObject:[UIFont systemFontOfSize:16]];
        [returnList addObject:UserFont(@"濑户字体setofont", @"ttf", 16)];
        [returnList addObject:UserFont(@"品如手写体", @"ttf", 16)];
        [returnList addObject:UserFont(@"手书体", @"ttf", 16)];
        [returnList addObject:UserFont(@"杨任东竹石体-Extralight", @"ttf", 16)];
        [returnList addObject:UserFont(@"站酷快乐体2016", @"ttf", 16)];
        [returnList addObject:UserFont(@"郑庆科黄油体", @"ttf", 16)];
        [returnList addObject:UserFont(@"Line+Font+超极细字型", @"ttf", 16)];
        [returnList addObject:UserFont(@"GenShinGothic-P-Light", @"ttf", 16)];
        returnListBlock(returnList);
        return;
    }
    else if (cellStyle == CellStyleBGColor) {
        [returnList addObject:UIColorMakeWithHex(@"#ffffff")];
        [returnList addObject:UIColorMakeWithHex(@"#e9e7ef")];
        [returnList addObject:UIColorMakeWithHex(@"#f0f0f4")];
        [returnList addObject:UIColorMakeWithHex(@"#e9f1f6")];
        [returnList addObject:UIColorMakeWithHex(@"#e3f9fd")];
        [returnList addObject:UIColorMakeWithHex(@"#d6ecf0")];
        [returnList addObject:UIColorMakeWithHex(@"#fffbf0")];
        [returnList addObject:UIColorMakeWithHex(@"#f2ecde")];
        [returnList addObject:UIColorMakeWithHex(@"#fcefe8")];
        [returnList addObject:UIColorMakeWithHex(@"#fff2df")];
        [returnList addObject:UIColorMakeWithHex(@"#f3f9f1")];
        [returnList addObject:UIColorMakeWithHex(@"#e0eee8")];
        [returnList addObject:UIColorMakeWithHex(@"#e0f0e9")];
        [returnList addObject:UIColorMakeWithHex(@"#c0ebd7")];
        returnListBlock(returnList);
        return;
    }
    else if (cellStyle == CellStyleImage) {
        [returnList addObject:@"相册卡片"];
        [returnList addObject:@"随机换背景"];
        [returnList addObject:@"换一换卡片"];
        [self getLeavelightListWithcategoryid:@"" Success:^(NSMutableArray * _Nonnull listArr) {
            for (ZDBaseModel *model in listArr) {
                [returnList addObject:[NSURL URLWithString:model.images]];
            }
            returnListBlock(returnList);
            return;
        } failed:^(NSString * _Nonnull error) {
            ;
        }];
    }
    else if (cellStyle == CellStyleTemplate) {
        [returnList addObject:@"模版_样式1"];
        [returnList addObject:@"模版_样式2"];
        [returnList addObject:@"模版_样式3"];
        [returnList addObject:@"模版_样式4"];
        [returnList addObject:@"模版_样式5"];
        [returnList addObject:@"模版_样式6"];
        [returnList addObject:@"模版_样式7"];
        [returnList addObject:@"模版_样式8"];
        returnListBlock(returnList);
        return;
    }
    else if (cellStyle == CellStyleTheSeal) {
        [returnList addObject:@"印章"];
        [returnList addObject:@"二维码"];
        returnListBlock(returnList);
        return;
    }
}


+(UIFont*)customFontWithLocationName:(NSString *)fileName fileType:(NSString *)style fontSize:(CGFloat)size
{
    if (!fileName || !style) {
        return nil;
    }
    
    NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:style];
    
    if (!path) {
        return nil;
    }
    NSURL *fontUrl = [NSURL fileURLWithPath:path];
    CGDataProviderRef fontDataProvider = CGDataProviderCreateWithURL((__bridge CFURLRef)fontUrl);
    CGFontRef fontRef = CGFontCreateWithDataProvider(fontDataProvider);
    CGDataProviderRelease(fontDataProvider);
    CTFontManagerRegisterGraphicsFont(fontRef, NULL);
    NSString *fontName = CFBridgingRelease(CGFontCopyPostScriptName(fontRef));
    UIFont *font = [UIFont fontWithName:fontName size:size];
    CGFontRelease(fontRef);
    return font;
}

#pragma mark - <QMUIAlbumViewControllerDelegate>
- (QMUIImagePickerViewController *)imagePickerViewControllerForAlbumViewController:(QMUIAlbumViewController *)albumViewController{
    QMUIImagePickerViewController *imagePickerViewController = [[QMUIImagePickerViewController alloc] init];
    imagePickerViewController.imagePickerViewControllerDelegate = self;
    imagePickerViewController.maximumSelectImageCount = 1;
    imagePickerViewController.view.tag = albumViewController.view.tag;
    return imagePickerViewController;
}

#pragma mark - <imagePickerViewControllerDelegate>
- (void)imagePickerViewController:(QMUIImagePickerViewController *)imagePickerViewController didFinishPickingImageWithImagesAssetArray:(NSMutableArray<QMUIAsset *> *)imagesAssetArray {
    // 储存最近选择了图片的相册，方便下次直接进入该相册
    [QMUIImagePickerHelper updateLastestAlbumWithAssetsGroup:imagePickerViewController.assetsGroup ablumContentType:kAlbumContentType userIdentify:nil];
    if (self.userSelectedBlock) {
        self.userSelectedBlock(self.cellStyle,0,[imagesAssetArray firstObject]);
    }
}

- (QMUIImagePickerPreviewViewController *)imagePickerPreviewViewControllerForImagePickerViewController:(QMUIImagePickerViewController *)imagePickerViewController {
    QMUIImagePickerPreviewViewController *imagePickerPreviewViewController = [[QMUIImagePickerPreviewViewController alloc] init];
    imagePickerPreviewViewController.view.tag = imagePickerViewController.view.tag;
    imagePickerPreviewViewController.toolBarBackgroundColor = UIColorMake(66, 66, 66);
    return imagePickerPreviewViewController;
}


@end
